package com.notes.romania;

import java.io.File;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.notes.romania.R.id;
import com.notes.romania.browser.FileBrowser;
import com.notes.romania.browser.NotificationBrowser;
import com.notes.romania.reminder.RemManager;
import com.notes.romania.reminder.Reminder;
import com.notes.romania.services.BackgroundService;

public class MainActivity extends FragmentActivity {
	
	private MainActivity THIS;
	
	private EditText note;
	private TextView datePicker;
	private TextView timePicker;
	private TextView soundPicker;
	
	private boolean datePicked = false;
	private boolean timePicked = false;
	
	private String soundPath;
	private boolean defaultSound = true;
	private int hour, minute;
	private int year, month, day;
	private int yearsDelay, daysDelay, hoursDelay, minutesDelay;
	private Reminder reminder;
	
	private final int SOUND_PATH_CODE = 1;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //****Rmove focus on start
        TextView dummy = (TextView)findViewById(id.dummy);
        dummy.setFocusableInTouchMode(true);
        dummy.requestFocus();
        //****
        
        THIS = this;
        
        //******Time/Date
        datePicker = (TextView)findViewById(R.id.textView1);
        datePicker.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				DialogFragment newFragment = new DatePickerFragment(THIS);
			    newFragment.show(getSupportFragmentManager(), "datePicker");
			}
		});
        timePicker = (TextView)findViewById(R.id.textView2);
        timePicker.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				DialogFragment newFragment = new TimePickerFragment(THIS);
			    newFragment.show(getSupportFragmentManager(), "timePicker");
			}
		});
        
        //*********Note
        note = (EditText)findViewById(R.id.Note);
        
        //********Add reminder
        Button add = (Button)findViewById(id.add_note);
        add.setOnClickListener(new View.OnClickListener() {
			public void onClick(View arg0) {
				if(datePicked && timePicked){
					saveReminder();
					startBackgroundService();
					
					THIS.finish();
				}
				else
					Toast.makeText(getApplicationContext(),
							"Date and time not picked", Toast.LENGTH_LONG).show();
			}
		});
        
        //******Pick sound
        soundPicker = (TextView)findViewById(id.textView3);
        soundPicker.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, FileBrowser.class);
				startActivityForResult(intent, SOUND_PATH_CODE);
			}
		});
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.app_menu, menu);

        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.reminders_item:
            	Intent intent = new Intent(this, NotificationBrowser.class);
            	startActivity(intent);
            	
            	break;
            case R.id.info_item:
            	Intent intent1 = new Intent(this, InfoActivity.class);
            	startActivity(intent1);
            	
            	break;
        }
        return true;
    }
    
    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) {     
    	super.onActivityResult(requestCode, resultCode, data); 
    	switch(requestCode) { 
    	case SOUND_PATH_CODE : { 
    		if (resultCode == Activity.RESULT_OK){
    			soundPath = data.getStringExtra("soundPath");
    			
    			File file = new File(soundPath);
    			soundPicker.setText(file.getName());
    			defaultSound = false;
    		}
    		break; 
    		} 
    	}
    }
    
    void startBackgroundService(){
    	Intent myIntent = new Intent(getApplicationContext(), BackgroundService.class);
        startService(myIntent);
    }
    
    void saveReminder(){
    	SharedPreferences settings = getSharedPreferences(RemManager.PREFS_NAME, Context.MODE_PRIVATE);
    	SharedPreferences.Editor editor = settings.edit();
    	
    	RemManager.setUp(settings,  editor);
    	
    	//Increment the total number of reminders
    	RemManager.setNrOfRem(RemManager.getNrOfRem() + 1);
    	
    	//Parse repeat textboxes
    	boolean repeat = parseStrings();
    	
    	//Create the reminder
    	reminder = new Reminder();
    	reminder.setId(RemManager.getNrOfRem());
    	reminder.setDateTime(year, month, day, hour, minute);
    	reminder.setRepeat(repeat);
    	reminder.setRepeatValues(yearsDelay, daysDelay, hoursDelay, minutesDelay);
    	reminder.setText(note.getText().toString() + " ");
    	reminder.setDefaultSound(defaultSound);
    	reminder.setSoundPath(soundPath);
    	
    	Toast.makeText(this, reminder.day + "/" + reminder.month + "/" + reminder.year + " " + reminder.hour + ":" + reminder.minute,
				Toast.LENGTH_LONG).show();
    	
    	//Write the reminder into memory
    	RemManager.putRem(reminder);
    }
    
    
    public void setTime(int hour, int minute){
    	this.hour = hour;
    	this.minute = minute;
    	
    	timePicker.setText(hour + " : " + minute);
    	timePicked = true;
    }
    
   
    
    public void setDate(int year, int month, int day){
    	this.day = day;
    	this.month = month;
    	this.year = year;
    	
    	datePicker.setText(day + " / " + (month + 1) + " / " + year);	//months start with 0
    	datePicked = true;
    }
    
    private boolean parseStrings(){
		 EditText years = (EditText)findViewById(id.editText1);
		 EditText days = (EditText)findViewById(id.editText2);
		 EditText hours = (EditText)findViewById(id.editText3);
		 EditText minutes = (EditText)findViewById(id.editText4);
		 
		 int filled = 0;
		 
		 if(years.getText().toString().equals(""))
			 yearsDelay = 0;
		 else{
			 yearsDelay = Integer.parseInt(years.getText().toString());
			 filled ++;
		 }
		 
		 if(days.getText().toString().equals(""))
			 daysDelay = 0;
		 else{
			 daysDelay = Integer.parseInt(days.getText().toString());
			 filled ++;
		 }
		 
		 if(hours.getText().toString().equals(""))
			 hoursDelay = 0;
		 else{
			 hoursDelay = Integer.parseInt(hours.getText().toString());
			 filled ++;
		 }
		 
		 if(minutes.getText().toString().equals(""))
			 minutesDelay = 0;
		 else{
			 minutesDelay = Integer.parseInt(minutes.getText().toString());
			 filled ++;
		 }
		
		 if(filled != 0)
			 return true;
		 return false;
	 }
}













class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
	MainActivity main;
	TimePickerFragment(MainActivity main){
		super();
		this.main = main;
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		// Use the current time as the default values for the picker
		final Calendar c = Calendar.getInstance();
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		
		// Create a new instance of TimePickerDialog and return it
		return new TimePickerDialog(getActivity(), this, hour, minute,
		DateFormat.is24HourFormat(getActivity()));
	}
	
	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
		main.setTime(hourOfDay, minute);
	}
}

class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
	MainActivity main;
	
	public DatePickerFragment(MainActivity main) {
		this.main = main;
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		// Use the current date as the default date in the picker
		final Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);
		
		// Create a new instance of DatePickerDialog and return it
			return new DatePickerDialog(getActivity(), this, year, month, day);
		}
		
		public void onDateSet(DatePicker view, int year, int month, int day) {
			main.setDate(year, month, day);
		}
}






